package com.ruoyi.report_tg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_tg.domain.vo.GeneralCharDataVo;
import com.ruoyi.report_wjjhl.domain.WdclzdgmdBaDetail;
import com.ruoyi.report_wjjhl.domain.bo.WdcljsbgBsInfoBo;
import com.ruoyi.report_wjjhl.domain.vo.WdclzdgmdBaDetailVo;
import com.ruoyi.report_wjjhl.mapper.WdclzdgmdBaDetailMapper;
import com.ruoyi.syrw.annotation.ComputeReportResult;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.common.LineUtil;
import com.ruoyi.syrw.common.QuadFunction;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_tg.domain.bo.TjssybgBsInfoBo;
import com.ruoyi.report_tg.domain.vo.TjssybgBsInfoVo;
import com.ruoyi.report_tg.domain.TjssybgBsInfo;
import com.ruoyi.report_tg.mapper.TjssybgBsInfoMapper;
import com.ruoyi.report_tg.service.ITjssybgBsInfoService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 土击实试验检测报告Service业务层处理
 *
 * @author zyb
 * @date 2024-10-28
 */
@RequiredArgsConstructor
@Service
@DSTransactional
public class TjssybgBsInfoServiceImpl implements ITjssybgBsInfoService {

    private final TjssybgBsInfoMapper baseMapper;
    private final WdclzdgmdBaDetailMapper detailMapper;

    /**
     * 查询土击实试验检测报告
     */
    @Override
    @FIllBasicInfo
    public TjssybgBsInfoVo queryById(Long excelId){
        TjssybgBsInfoVo tjssybgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<WdclzdgmdBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<WdclzdgmdBaDetail>()
            .eq(WdclzdgmdBaDetail::getExcelId, excelId));
        if (CollUtil.isNotEmpty(baDetailVos)) {
            tjssybgBsInfoVo.setBaDetailVos(baDetailVos);
        }
        // 计算
        compute(tjssybgBsInfoVo);
        // 如果已经有值了则不需要计算结论。
        if (StrUtil.isNotEmpty(tjssybgBsInfoVo.getJiancjl()) && !"检测结论：".equals(tjssybgBsInfoVo.getJiancjl())) {
            return tjssybgBsInfoVo;
        }
        return jcjl(tjssybgBsInfoVo);
    }

    /**
     * 查询土击实试验检测报告列表
     */
    @Override
    public TableDataInfo<TjssybgBsInfoVo> queryPageList(TjssybgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TjssybgBsInfo> lqw = buildQueryWrapper(bo);
        Page<TjssybgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询土击实试验检测报告列表
     */
    @Override
    public List<TjssybgBsInfoVo> queryList(TjssybgBsInfoBo bo) {
        LambdaQueryWrapper<TjssybgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TjssybgBsInfo> buildQueryWrapper(TjssybgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TjssybgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, TjssybgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, TjssybgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), TjssybgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), TjssybgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), TjssybgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), TjssybgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), TjssybgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), TjssybgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), TjssybgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsj()), TjssybgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), TjssybgBsInfo::getJiancrq, bo.getJiancrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), TjssybgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), TjssybgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), TjssybgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), TjssybgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), TjssybgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getQuywz()), TjssybgBsInfo::getQuywz, bo.getQuywz());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), TjssybgBsInfo::getWeitrwbh, bo.getWeitrwbh());
        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), TjssybgBsInfo::getTuycd, bo.getTuycd());
        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), TjssybgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), TjssybgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), TjssybgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), TjssybgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), TjssybgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), TjssybgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), TjssybgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), TjssybgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), TjssybgBsInfo::getPandyjIds, bo.getPandyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancff()), TjssybgBsInfo::getJiancff, bo.getJiancff());
        lqw.eq(bo.getMeicjs() != null, TjssybgBsInfo::getMeicjs, bo.getMeicjs());
        lqw.eq(StringUtils.isNotBlank(bo.getJiehlzl()), TjssybgBsInfo::getJiehlzl, bo.getJiehlzl());
        lqw.eq(StringUtils.isNotBlank(bo.getChanpbl()), TjssybgBsInfo::getChanpbl, bo.getChanpbl());
        lqw.eq(bo.getShiyzdlj() != null, TjssybgBsInfo::getShiyzdlj, bo.getShiyzdlj());
        lqw.eq(bo.getTongrj() != null, TjssybgBsInfo::getTongrj, bo.getTongrj());
        lqw.eq(bo.getJiczl() != null, TjssybgBsInfo::getJiczl, bo.getJiczl());
        lqw.eq(bo.getLuoj() != null, TjssybgBsInfo::getLuoj, bo.getLuoj());
        lqw.eq(bo.getJiehljl() != null, TjssybgBsInfo::getJiehljl, bo.getJiehljl());
        lqw.eq(bo.getZuidgmd1() != null, TjssybgBsInfo::getZuidgmd1, bo.getZuidgmd1());
        lqw.eq(bo.getZuidgmd2() != null, TjssybgBsInfo::getZuidgmd2, bo.getZuidgmd2());
        lqw.eq(bo.getZuidgmdjz() != null, TjssybgBsInfo::getZuidgmdjz, bo.getZuidgmdjz());
        lqw.eq(bo.getZuijhsl1() != null, TjssybgBsInfo::getZuijhsl1, bo.getZuijhsl1());
        lqw.eq(bo.getZuijhsl2() != null, TjssybgBsInfo::getZuijhsl2, bo.getZuijhsl2());
        lqw.eq(bo.getZuijhsljz() != null, TjssybgBsInfo::getZuijhsljz, bo.getZuijhsljz());
        lqw.eq(bo.getXiuzhpjzjhsl() != null, TjssybgBsInfo::getXiuzhpjzjhsl, bo.getXiuzhpjzjhsl());
        lqw.eq(bo.getXiuzhpjzdgmd() != null, TjssybgBsInfo::getXiuzhpjzdgmd, bo.getXiuzhpjzdgmd());
        lqw.eq(bo.getExcelResult() != null, TjssybgBsInfo::getExcelResult, bo.getExcelResult());
        return lqw;
    }

    /**
     * 新增土击实试验检测报告
     */
    @Override
    public Boolean insertByBo(TjssybgBsInfoBo bo) {
        TjssybgBsInfo add = BeanUtil.toBean(bo, TjssybgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详细 12次
            ArrayList<WdclzdgmdBaDetail> details = new ArrayList<>(10);
            for (long i = 1; i <= 10L; i++) {
                details.add(new WdclzdgmdBaDetail(add.getExcelId(), i));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改土击实试验检测报告
     */
    @Override
    @ComputeReportResult
    public Boolean updateByBo(TjssybgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        TjssybgBsInfo update = BeanUtil.toBean(bo, TjssybgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos(), WdclzdgmdBaDetail.class));
        }
        return flag;
    }

    private void fillExcelResult(TjssybgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
//            for (WdclzdgmdBaDetailVo detailVo : bo.getBaDetailVos()) {
//                if ("不符合".equals(detailVo.getJiegpd())) {
//                    bo.setExcelResult(0);
//                    return;
//                }
//            }
            bo.setExcelResult(1);
        }
        bo.setExcelResult(0);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TjssybgBsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除土击实试验检测报告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TjssybgBsInfoVo compute(TjssybgBsInfoVo vo) {
        // 1. 参数判断 如果有任何一个为空,则 直接原样返回
        List<WdclzdgmdBaDetailVo> baDetailVos = vo.getBaDetailVos();
        if (CollUtil.isEmpty(baDetailVos)) {
            return vo;
        }
        for (WdclzdgmdBaDetailVo detailVo : baDetailVos) {
            if (BigDecimalUtil.isAnyOneEmpty(detailVo.getGanmd(), detailVo.getHanslpjz())) {
                return vo;
            }
        }
        // 2. 计算
        for (int index = 0 ; index <=1 ; index ++) {
            double[][] data = new double[5][2];
            for (int i = 0; i < 5; i++) {
                data[i][0] = baDetailVos.get(i+index*5).getHanslpjz().doubleValue();
                data[i][1] = baDetailVos.get(i+index*5).getGanmd().doubleValue();
            }
            QuadFunction quadFuncLine = LineUtil.getQuadFuncLine(data);
//            vo.setZuijhsl(BigDecimalUtil.defaultValue((quadFuncLine.getB() / ((0 - quadFuncLine.getA()) * 2)), 2));
//            vo.setZuidgmd(BigDecimalUtil.defaultValue(quadFuncLine.getY(vo.getZuijhsl().doubleValue()), 2));
            // 3.1 画图所需要的 data  参与画线 不展示 不突出辅助线
            List<GeneralCharDataVo> charData = generateData(quadFuncLine, data[0][0], data[4][0]);
            // 3.2 其他的点 不参与画线 展示 不突出辅助线
            for (double[] datum : data) {
                charData.add(new GeneralCharDataVo(datum, "010"));
            }
            // 3.3 不参与画线 展示 突出辅助线 (此处是两个图，故只在第1个图中体现即可。)
            if (index == 0) {
                charData.add(new GeneralCharDataVo(new double[]{vo.getZuijhsljz().doubleValue(), vo.getZuidgmdjz().doubleValue()}, "011"));
            }
            vo.setChartData(index, charData);
        }
        return vo;
    }

    @Override
    public TjssybgBsInfoVo jcjl(TjssybgBsInfoVo vo) {
        //        if (StrUtil.isEmpty(vo.getPandyj())) {
//            return vo;
//        }
        vo.setJiancjl("检测结论：依据《公路土工试验工程》JTG 3430-2020检测，该土样最大干密度实测值为" + BigDecimalUtil.toStringDefaultEmpty(vo.getZuidgmdjz()) + "g/cm3, 最佳含水率实测值为"
            + BigDecimalUtil.toStringDefaultEmpty(vo.getZuijhsljz()) + "%。");
        return vo;
    }

    private List<GeneralCharDataVo> generateData(QuadFunction quadFuncLine, double start, double end) {
        List<GeneralCharDataVo> result = new ArrayList<>(600);
        for (double i = start; i <= end; i += 0.2) {
            result.add(new GeneralCharDataVo(new double[]{BigDecimalUtil.defaultValue(i,2).doubleValue(), quadFuncLine.getY(i)}, "100"));
        }
        return result;

    }
}
